package model

import (
	"bytes"
	"crypto/ecdsa"
	"encoding/json"
	"encoding/pem"
	"github.com/emmansun/gmsm/sm2"
	"github.com/emmansun/gmsm/smx509"
	"os"
)

type Key struct {
	PUBKEY PublicKey
	PRIKEY PrivateKey
}

func (key *Key) ToBytes() []byte {
	marshal, err := json.Marshal(key)
	if err != nil {
		panic(err)
	}
	return marshal
}

type PrivateKey struct {
	Data []byte
}

type PublicKey struct {
	Data []byte
}

func (p *PrivateKey) ToPrivateKey() *ecdsa.PrivateKey {
	b1 := new(bytes.Buffer)
	b1.Write(p.Data)
	decode1, _ := pem.Decode(b1.Bytes())
	prikey, err := smx509.ParsePKCS8PrivateKey(decode1.Bytes)
	if err != nil {
		panic(err)
	}
	return &prikey.(*sm2.PrivateKey).PrivateKey
}

func (p *PublicKey) ToPublicKey() *ecdsa.PublicKey {
	//解析公钥
	b2 := new(bytes.Buffer)
	b2.Write(p.Data)
	decode2, _ := pem.Decode(b2.Bytes())
	key, err := smx509.ParsePKIXPublicKey(decode2.Bytes)
	if err != nil {
		panic(err)
	}
	return key.(*ecdsa.PublicKey)
}

func (key *Key) ToFile() error {
	pubFile, err := os.Create("public.pem")
	priFile, err := os.Create("private.pem")
	if err != nil {
		panic(err)
	}
	_, err = pubFile.Write(key.PUBKEY.Data)
	if err != nil {
		panic(err)
	}
	_, err = priFile.Write(key.PRIKEY.Data)
	if err != nil {
		panic(err)
	}
	return err
}
